package task

import (
	"io"
	"path"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type ContestProblemsTask struct {
	TaskBase
}

type contestProblem struct {
	ContestId string    `json:"contestId"`
	Porblems  []problem `json:"problems"`
}
type problem struct {
	Order       string `json:"order"`
	Name        string `json:"name"`
	Url         string `json:"url"`
	TimeLimit   string `json:"timeLimit"`
	MemoryLimit string `json:"memoryLimit"`
}

func (c ContestProblemsTask) GetParseFunc(r io.Reader) interface{} {

	doc, err := goquery.NewDocumentFromReader(r)
	if err != nil {
		panic("parse html fail")
	}
	table := doc.Find(".problems").Find("tbody")
	trs := table.Find("tr")
	contestProblems := &contestProblem{}
	contestProblems.Porblems = make([]problem, 0, 8)
	contestProblems.ContestId = path.Base(c.url)
	for i := 1; i < trs.Length(); i++ {
		t := problem{}
		t.Order = trim(trs.Eq(i).Find("td").Eq(0).Find("a").Text())
		t.Name = trim(trs.Eq(i).Find("td").Eq(1).Find("a").Text())
		t.Url = "https://codeforces.com" + trs.Eq(i).Find("td").Eq(0).Find("a").AttrOr("href", "")
		ts := strings.Split(strings.ReplaceAll(trim(trs.Eq(i).Find("td").Eq(1).Find(".notice").Text()), " ", ""), "\n")
		ts1 := strings.Split(ts[len(ts)-1], ",")
		t.TimeLimit = ts1[0]
		t.MemoryLimit = ts1[1]
		contestProblems.Porblems = append(contestProblems.Porblems, t)
	}
	return *contestProblems

}
func NewContestProblemTask(contestId string) ITask {
	return &ContestProblemsTask{
		TaskBase{
			url: "https://codeforces.com/contest/" + contestId,
		},
	}
}
